<template>
    <div>
        <el-card class="!border-none mb-4" shadow="never">
            <el-form class="mb-[-16px]" :model="queryParams" inline>
                <el-form-item label="广告主ID" prop="ad_account_id">
                    <el-select
                        v-model="queryParams.ad_account_id"
                        filterable
                        remote
                        reserve-keyword
                        placeholder="请选择广告主ID"
                        :remote-method="remoteSearchCorporation"
                        :loading="corporationLoading"
                         style="width: 380px !important;"
                        clearable
                    >
                        <el-option
                            v-for="item in corporationOptions"
                            :key="item.ad_account_id"
                            :label="`${item.ad_account_id}（${item.corporation_name}）`"
                            :value="item.ad_account_id"
                        >
                            <div class="flex flex-col">
                                <span>{{ item.ad_account_id }}</span>
                                <span class="text-gray-400 text-xs">{{ item.corporation_name }}</span>
                            </div>
                        </el-option>
                    <template #footer>
                            <div class="flex justify-between items-center p-2 border-t">
                                <span class="text-sm text-gray-500">共 {{ corporationTotal }} 项</span>
                                <el-pagination
                                    small
                                    layout="prev, pager, next"
                                    :total="corporationTotal"
                                    :page-size="corporationPageSize"
                                    :current-page="corporationCurrentPage"
                                    @current-change="handleCorporationPageChange"
                                />
                            </div>
                    </template>
                 </el-select>
                </el-form-item>
                <el-form-item label="广告主名称" prop="corporation_name">
                    <el-input class="w-[280px]" v-model="queryParams.corporation_name" clearable
                        placeholder="请输入广告主名称" />
                </el-form-item>
                <el-form-item label="广告组ID" prop="ad_group_id">
                    <el-input class="w-[280px]" v-model="queryParams.ad_group_id" clearable placeholder="请输入广告组ID" />
                </el-form-item>
                <el-form-item label="广告组名称" prop="ad_group_name">
                    <el-input class="w-[280px]" v-model="queryParams.ad_group_name" clearable placeholder="请输入广告组名称" />
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" @click="resetPage">查询</el-button>
                    <el-button @click="resetParams">重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>
        <el-card class="!border-none" v-loading="pager.loading" shadow="never">
            <div class="mt-4">
                <el-table :data="pager.lists" @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="55" />
                    <el-table-column label="广告主账户" show-overflow-tooltip>
                        <template #default="scope">
                            <div>{{ scope.row.corporation_name }}</div>
                            <div class="text-gray-400 text-sm mt-1 flex items-center">
                                <span class="inline-block w-[90px]">ID:</span>
                                <span>{{ scope.row.ad_account_id }}</span>
                                <el-icon class="ml-2 cursor-pointer" style="color: #4a5dff;" @click="copyToClipboard(scope.row.ad_account_id)">
                                    <CopyDocument />
                                </el-icon>
                            </div>
                            <div class="text-gray-400 text-sm mt-1 flex items-center">
                                <span class="inline-block w-[90px]">授权账户ID:</span>
                                <span>{{ scope.row.account_id }}</span>
                                <el-icon class="ml-2 cursor-pointer" style="color: #4a5dff;" @click="copyToClipboard(scope.row.account_id)">
                                    <CopyDocument />
                                </el-icon>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column label="广告组ID" prop="ad_group_id" show-overflow-tooltip>
                        <template #default="scope">
                            <div class="flex items-center">
                                <span>{{ scope.row.ad_group_id }}</span>
                                <el-icon class="ml-2 cursor-pointer" style="color: #4a5dff;" @click="copyToClipboard(scope.row.ad_group_id)">
                                    <CopyDocument />
                                </el-icon>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column label="广告组名称" prop="ad_group_name" show-overflow-tooltip>
                        <template #default="scope">
                            <div class="flex items-center">
                                <span>{{ scope.row.ad_group_name }}</span>
                                <el-icon class="ml-2 cursor-pointer" style="color: #4a5dff;" @click="copyToClipboard(scope.row.ad_group_name)">
                                    <CopyDocument />
                                </el-icon>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column label="24小时投放" prop="24hours_state">
                        <template #default="scope">
                            <el-switch active-text="开启" :active-value="1" active-color="#2fa1fa" inactive-text="关闭"
                                :inactive-value="2" inactive-color="#9c9c9c" v-model="scope.row.hour_push_state"
                                @click="handle24HousePlacement(scope.row)">

                            </el-switch>
                        </template>
                    </el-table-column>

                    <el-table-column label="操作" width="430" fixed="right">
                        <template #default="{ row }">

                            <el-button v-perms="['ads.tencent_advertising_user_ad_list/placement']" type="primary" link
                                @click="handlePlacement(row)">
                                投放
                            </el-button>
                            <el-button v-perms="['ads.tencent_advertising_user_ad_list/placement']" type="primary" link
                                @click="handlePlacementRefresh(row)">
                                快速投放
                            </el-button>

                            <el-button v-perms="['ads.tencent_advertising_user_ad_list/placement']" type="primary" link
                                @click="handlePlacementLog(row)">
                                投放记录
                            </el-button>

                            <el-button 
                                v-perms="['ads.tencent_advertising_user_ad_list/placement']" 
                                type="primary" 
                                link
                                @click="handleBlacklist(row)">
                                投放黑名单
                            </el-button>

                            <el-button 
                                v-perms="['ads.tencent_advertising_user_ad_list/placement']" 
                                type="primary" 
                                link
                                @click="handleWechatList(row)">
                                关联微信号
                            </el-button>

                            <el-button
                                v-perms="['ads.tencent_advertising_user_ad_list/delete']"
                                type="danger"
                                link
                                @click="handleDelete(row.id)">
                                删除
                            </el-button>

                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <div class="flex mt-4 justify-end">
                <pagination v-model="pager" @change="getLists" />
            </div>
        </el-card>
        <placement-popup v-if="showPlacement" ref="placementRef" :dict-data="dictData" @success="getLists"
            @close="showPlacement = false" />
        <placement-log-popup v-if="showPlacementLog" ref="placementLogRef" :ad_group_id="showPlacementLogAdGroupId"
            @success="showPlacementLog = false" @close="showPlacementLog = false" />

        <WechatListPopup v-if="showWechatList" ref="wechatListRef" 
        :ad_group_id="wechatListAdGroupId" @close="showWechatList = false"/>

        <BlacklistPopup v-if="showBlacklist" ref="blacklistRef" 
        :ad_group_id="blacklistAdGroupId" @close="showBlacklist = false"/>

    </div>
</template>

<script lang="ts" setup name="tencentAdvertisingUserAdListLists">
import {
    apiTencentAdvertisingUserAdList24HourPlacement,
    apiTencentAdvertisingUserAdListDelete,
    apiTencentAdvertisingUserAdListLists,
    apiTencentAdvertisingUserAdListPlacementRefresh
} from '@/api/tencent_advertising_user_ad_list'
import { useDictData } from '@/hooks/useDictOptions'
import { usePaging } from '@/hooks/usePaging'
import feedback from '@/utils/feedback'
// eslint-disable-next-line @typescript-eslint/no-unused-vars
import { timeFormat } from '@/utils/util'

import PlacementPopup from './placement.vue'
import PlacementLogPopup from './placement_log.vue'
import WechatListPopup from './wechat_list.vue'
import BlacklistPopup from './blacklist.vue'
import {
    ElLoading,
    ElMessage,
    ElMessageBox,
    type ElMessageBoxOptions,
    ElNotification
} from 'element-plus'
import { CopyDocument } from '@element-plus/icons-vue'  // 导入复制图标
import axios from 'axios'
import useUserStore from '@/stores/modules/user'


const placementRef = shallowRef<InstanceType<typeof PlacementPopup>>()
const placementLogRef = shallowRef<InstanceType<typeof PlacementLogPopup>>()
const wechatListRef = shallowRef<InstanceType<typeof WechatListPopup>>()
    const blacklistRef = shallowRef<InstanceType<typeof BlacklistPopup>>()
// 是否显示投放框
const showPlacement = ref(false)

// 是否显示投放记录框
const showPlacementLog = ref(false)
const showPlacementLogAdGroupId = ref()

// 新增弹窗相关代码
const showWechatList = ref(false)
const wechatListAdGroupId = ref()
const handleWechatList =async (data: any) => {
    wechatListAdGroupId.value = data.ad_group_id
    showWechatList.value = true
    await nextTick()
    wechatListRef.value?.open('wechat_list')
}

// 新增黑名单弹窗相关代码
const showBlacklist = ref(false)
const blacklistAdGroupId = ref()
const handleBlacklist = async (data: any) => {
    blacklistAdGroupId.value = data.ad_group_id
    showBlacklist.value = true
    await nextTick()
    blacklistRef.value?.open('blacklist')
}

// 查询条件
const queryParams = reactive({
    tenant_id: '',
    account_id: '',
    ad_account_id: '',
    corporation_name: '',
    ad_group_id: '',
    ad_group_name: '',
    dynamic_creative_id: '',
    dynamic_creative_name: '',
})

// 选中数据
const selectData = ref<any[]>([])

// 表格选择后回调事件
const handleSelectionChange = (val: any[]) => {
    selectData.value = val.map(({ id }) => id)
}

// 获取字典数据
const { dictData } = useDictData('')

// 分页相关
const { pager, getLists, resetParams, resetPage } = usePaging({
    fetchFun: apiTencentAdvertisingUserAdListLists,
    params: queryParams
})


// 投放
const handlePlacement = async (data: any) => {
    showPlacement.value = true
    await nextTick()
    placementRef.value?.open('placement')
    placementRef.value?.setFormData(data)
}

//投放记录
const handlePlacementLog = async (data: any) => {
    showPlacementLogAdGroupId.value = data.ad_group_id
    showPlacementLog.value = true
    await nextTick()
    placementLogRef.value?.open('placement_log')
}

// 投放刷新
const handlePlacementRefresh = async (data: any) => {
    const loading = ElLoading.service({
        lock: true,
        text: '投放中...'
    })
    let res =await  apiTencentAdvertisingUserAdListPlacementRefresh(data)
    console.log(res,'resresresresresresresresresresresresresres');
    
    if (res.data.code == 1) {
        ElMessage.success(res.data.msg)
    } else {
        ElMessage.error(res.data.msg)
    }
    loading.close()
}

// 删除
const handleDelete = async (id: number | any[]) => {
    await feedback.confirm('确定要删除？')
    await apiTencentAdvertisingUserAdListDelete({ id })
    getLists()
}

const handle24HousePlacement = async (data: any[]) => {
    const loading = ElLoading.service({
        lock: true,
        text: '投放开启中...'
    })
    let params = { "id": data.id, "hour_push_state": data.hour_push_state }
    let res = await apiTencentAdvertisingUserAdList24HourPlacement(params)
    if (res.data.code == 1) {
        ElMessage.success(res.data.msg)
    } else {
        ElMessage.error(res.data.msg)
    }
    loading.close()
    getLists()
}

// 广告主名称下拉选项
const corporationOptions = ref([])
const corporationLoading = ref(false)
const corporationTotal = ref(0)
const corporationCurrentPage = ref(1)
const corporationPageSize = ref(10)
const corporationKeyword = ref('')

/**
 * 远程搜索广告主名称
 * @param {string} query - 搜索关键词
 */
 const remoteSearchCorporation = (query) => {
    corporationKeyword.value = query
    corporationCurrentPage.value = 1
    fetchCorporationOptions()
}

const userStore = useUserStore()
/**
 * 获取广告主名称选项
 */
 const fetchCorporationOptions = async () => {
    corporationLoading.value = true
    try {
        const params = {
            page: corporationCurrentPage.value,
            limit: corporationPageSize.value,
            ad_account_id: corporationKeyword.value,
        }
        const headers = {
            "Token": userStore.token,
        }
        
        const response = await axios.get('https://adsapi.hxjpayment.cn/tenantapi/ads.tencent_advertising_user_ad/lists', { params,headers })
        
        if (response.data.code === 1) {
            corporationOptions.value = response.data.data.lists || []
            corporationTotal.value = response.data.data.count || 0
        } else {
            ElMessage.error(response.data.msg || '获取广告主列表失败')
            corporationOptions.value = []
            corporationTotal.value = 0
        }
    } catch (error) {
        console.error('获取广告主列表出错:', error)
        ElMessage.error('获取广告主列表失败')
        corporationOptions.value = []
        corporationTotal.value = 0
    } finally {
        corporationLoading.value = false
    }
}

/**
 * 处理广告主名称分页变化
 * @param {number} page - 页码
 */
 const handleCorporationPageChange = (page) => {
    corporationCurrentPage.value = page
    fetchCorporationOptions()
}

// 初始加载广告主名称选项
onMounted(() => {
    fetchCorporationOptions()
})

getLists()
// 复制到剪贴板功能
const copyToClipboard = (text) => {
    navigator.clipboard.writeText(text).then(() => {
        ElMessage.success('复制成功')
    }).catch(() => {
        ElMessage.error('复制失败')
    })
}
</script>

<style scoped>
/* 确保下拉选项宽度与选择器一致 */
:deep(.el-select-dropdown__wrap) {
  min-width: 380px;
}
</style>
